package com.itheima.bakery.demos.web.config;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity<String> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException e) {
        // 获取参数名
        String name = e.getName();
        // 获取期望的类型
        Class<?> requiredType = e.getRequiredType();
        // 创建错误消息
        String message = "请求参数 '" + name + "' 类型错误，应为 '" + requiredType.getSimpleName() + "'";
        // 返回400错误响应
        return ResponseEntity.badRequest().body(message);
    }
}
